package vip.xumy.picture.ctrl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import vip.xumy.admin.verify.controller.PublicController;
import vip.xumy.admin.verify.pojo.User;
import vip.xumy.core.pojo.base.BasePageParam;
import vip.xumy.core.pojo.com.AjaxResponse;
import vip.xumy.core.pojo.com.PageResponse;
import vip.xumy.picture.service.MyUserService;

/**
 * Do not use for any commercial purposes without permission
 * 
 * @author: mengyxu
 * @date: 2022年1月7日
 */

@RestController
@RequestMapping("my/user")
public class MyUserController {
	@Autowired
	private MyUserService userService;

	@GetMapping
	public PageResponse<User> save(BasePageParam param, HttpServletRequest request) {
		User user = getUser(request);
		PageResponse<User> rsp = new PageResponse<>();
		if (!"1".equals(user.getPermission())) {
			rsp.setRows(new ArrayList<User>());
			rsp.setTotal(0L);
		} else {
			Page<User> pages = PageHelper.startPage(param.getPage(), param.getSize());
			List<User> list = userService.list();
			rsp.setRows(list);
			rsp.setTotal(pages.getTotal());
		}
		return rsp;
	}

	@PostMapping
	public AjaxResponse save(@RequestBody User user) {
		userService.save(user);
		return AjaxResponse.successed();
	}

	@DeleteMapping
	public AjaxResponse delete(@RequestBody User user) {
		userService.delete(user.getUserId());
		return AjaxResponse.successed();
	}
	
	public static User getUser(HttpServletRequest request) {
		return (User)request.getSession().getAttribute(PublicController.KEY);
	}
	
	public static String getUserId(HttpServletRequest request) {
		return getUser(request).getUserId();
	}

}
